<template>
    <view class="container">
        <public-module leftIcon="arrow-left" :title="title" />
        
        <!-- 训练区域 -->
        <view class="training-area">
            <!-- 训练状态 - 包含进度条 -->
            <view class="status-card" v-if="!showSummary">
                <!-- 进度条 -->
                <view class="progress-container">
                    <view class="progress-bar">
                        <view class="progress-fill" :style="{ width: progressPercentage + '%' }"></view>
                    </view>
                </view>
                
                <!-- 状态信息 -->
                <view class="status-info">
                    <!-- 正向计时器 -->
                    <view class="timer-container">
                        <text class="status-label">用时</text>
                        <text class="timer-text" :key="timerUpdateKey">{{ formattedTime }}</text>
                    </view>
                    <view class="score-board">
                        <view class="score-item">
                            <text class="score-label">正确</text>
                            <text class="score-value correct">{{ correctCount }}</text>
                        </view>
                        <view class="score-item">
                            <text class="score-label">错误</text>
                            <text class="score-value wrong">{{ wrongCount }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 题目区域 -->
            <view class="question-area" v-if="!showSummary">
                <view class="question-card">
                    <text class="question-text">{{ currentQuestion.question }}</text>                
                    <!-- 输入区域 -->
                    <view class="input-area">
                        <input type="text" v-model="userAnswer" :placeholder="getInputPlaceholder()" 
                               :disabled="isChecking" readonly @focus="blurInput" @confirm="checkAnswer" 
                               :class="{ 'correct-input': lastAnswerCorrect, 'wrong-input': lastAnswerWrong }"/>
                    </view>
                </view>
            </view>

            <!-- 数字键盘 -->
            <view class="keyboard-container" v-if="!showSummary">
                <!-- 小键盘和震动开关 -->
                <view class="settings-row">
                    <view class="setting-item">
                        <text>小键盘</text>
                        <switch :checked="smallKeyboardEnabled" @change="toggleSmallKeyboard" />
                    </view>
                    <view class="setting-item">
                        <text>震动</text>
                        <switch :checked="vibrationEnabled" @change="vibrationEnabled = $event.detail.value" />
                    </view>
                </view>
                <view class="number-keyboard" :class="{ 'small-keyboard': smallKeyboardEnabled }">
                    <view class="keyboard-row">
                        <button class="key" @touchstart="handleTouchStart('1')" @touchend="handleTouchEnd('1')">1</button>
                        <button class="key" @touchstart="handleTouchStart('2')" @touchend="handleTouchEnd('2')">2</button>
                        <button class="key" @touchstart="handleTouchStart('3')" @touchend="handleTouchEnd('3')">3</button>
                        <button class="key delete" @touchstart="handleTouchStart('delete')" @touchend="handleTouchEnd('delete')">⌫</button>
                    </view>
                    <view class="keyboard-row">
                        <button class="key" @touchstart="handleTouchStart('4')" @touchend="handleTouchEnd('4')">4</button>
                        <button class="key" @touchstart="handleTouchStart('5')" @touchend="handleTouchEnd('5')">5</button>
                        <button class="key" @touchstart="handleTouchStart('6')" @touchend="handleTouchEnd('6')">6</button>
                        <button class="key clear" @touchstart="handleTouchStart('restart')" @touchend="handleTouchEnd('restart')">重来</button>
                    </view>
                    <view class="keyboard-row">
                        <button class="key" @touchstart="handleTouchStart('7')" @touchend="handleTouchEnd('7')">7</button>
                        <button class="key" @touchstart="handleTouchStart('8')" @touchend="handleTouchEnd('8')">8</button>
                        <button class="key" @touchstart="handleTouchStart('9')" @touchend="handleTouchEnd('9')">9</button>
                        <button class="key confirm" @touchstart="handleTouchStart('confirm')" @touchend="handleTouchEnd('confirm')">确定</button>
                    </view>
                    <view class="keyboard-row">
                        <button class="key" @touchstart="handleTouchStart('.')" @touchend="handleTouchEnd('.')" v-if="needsDecimal()">.</button>
                        <button class="key" @touchstart="handleTouchStart('-')" @touchend="handleTouchEnd('-')" v-else-if="needsMinus()">-</button>
                        <button class="key" @touchstart="handleTouchStart(' ')" @touchend="handleTouchEnd('')" v-else style="visibility: hidden;"></button>
                        <button class="key" @touchstart="handleTouchStart('0')" @touchend="handleTouchEnd('0')">0</button>
                        <button class="key" @touchstart="handleTouchStart('%')" @touchend="handleTouchEnd('%')" v-if="needsPercent()">%</button>
                        <button class="key" @touchstart="handleTouchStart(' ')" @touchend="handleTouchEnd('')" v-else style="visibility: hidden;"></button>
                    </view>
                </view>
            </view>
        </view>

        <!-- 训练总结区域 -->
        <view class="summary-area" v-if="showSummary">
            <view class="summary-header">
                <text class="summary-title">训练总结</text>
                <view class="summary-stats">
                    <view class="stat-item">
                        <text class="stat-label">总题量</text>
                        <text class="stat-value">{{ questionCount }} 题</text>
                    </view>
                    <view class="stat-item">
                        <text class="stat-label">正确率</text>
                        <text class="stat-value" :class="scoreClass">
                            {{ questionCount > 0 ? ((correctCount / questionCount) * 100).toFixed(1) : '0.0' }}%
                        </text>
                    </view>
                    <view class="stat-item">
                        <text class="stat-label">总用时</text>
                        <text class="stat-value">{{ formattedTime }}</text>
                    </view>
                </view>
                
                <!-- 全对提示 -->
                <view class="record-status" v-if="wrongCount === 0 && isBestRecord">
                    <text class="perfect-score">✨ 全对！刷新最好成绩</text>
                </view>
                <view class="record-status" v-else-if="wrongCount === 0 && !isBestRecord">
                    <text class="good-score">✨ 全对！但未超越最好成绩</text>
                </view>
                <view class="record-status" v-else>
                    <text class="imperfect-score">⚠️ 存在错题，记录未保存</text>
                </view>
            </view>

            <view class="summary-content-wrapper">
                <view class="summary-content">
                    <view class="record-header">
                        <text>序号</text>
                        <text>题目</text>
                        <text>正确答案</text>
                        <text>你的答案</text>
                        <text>结果</text>
                    </view>

                    <view v-for="(record, index) in questionRecords" :key="index" class="question-record"
                        :class="{'correct': record.isCorrect, 'wrong': !record.isCorrect}">
                        <text>{{ index + 1 }}</text>
                        <text>{{ record.question }}</text>
                        <text>{{ formatAnswer(record.correctAnswer) }}</text>
                        <text>{{ formatAnswer(parseFloat(record.userAnswer)) }}</text>
                        <text>{{ record.isCorrect ? '√' : '×' }}</text>
                    </view>
                </view>
            </view>

            <view class="action-buttons">
                <button class="restart-btn" @click="restartTraining">重新开始</button>
                <button class="save-btn" @click="saveImage">保存记录</button>
            </view>
        </view>
    </view>
</template>

<script>
    import { estimateRecordAdd } from "@/config/api.js";
    
    export default {
        data() {
            return {
                title: '答题训练',
                // 训练参数
                trainingType: '', // 'basic' 或 'special'
                trainingMode: '',
                methodType: '',
                methodTitle: '',
                questionCount: 10,
                errorRange: 5,
                
                // 训练状态
                isChecking: false,
                totalMilliseconds: 0,
                timerInterval: null,
                timerUpdateKey: 0,
                formattedTime: '00:00.0',
                correctCount: 0,
                wrongCount: 0,
                currentQuestionIndex: 0,
                userAnswer: '',
                currentQuestion: {
                    question: '',
                    answer: null,
                    explanation: '',
                    errorRange: 0
                },
                questionRecords: [],
                showSummary: false,
                lastAnswerCorrect: false,
                lastAnswerWrong: false,
                isBestRecord: false, // 是否为最好成绩
                
                // 键盘和震动设置
                vibrationEnabled: false,
                touchedKeys: {},
                smallKeyboardEnabled: false
            };
        },
        
        computed: {
            // 进度百分比
            progressPercentage() {
                return (this.currentQuestionIndex / this.questionCount) * 100;
            },
            // 分数样式类
            scoreClass() {
                const rate = this.correctCount / this.questionCount;
                if (rate >= 0.8) return 'high-score';
                if (rate >= 0.6) return 'medium-score';
                return 'low-score';
            },
            // 是否是尾数法训练
            isTailMethod() {
                return this.trainingType === 'special' && this.methodType === 'tail-method';
            }
        },
        
        methods: {
            // 开始训练 - 初始化计时
            startTraining() {
                // 清除现有计时器
                if (this.timerInterval) {
                    clearInterval(this.timerInterval);
                    this.timerInterval = null;
                }
                
                // 重置计时数据
                this.totalMilliseconds = 0;
                this.formattedTime = '00:00.0';
                this.timerUpdateKey = 0;
                
                // 重置训练状态
                this.correctCount = 0;
                this.wrongCount = 0;
                this.currentQuestionIndex = 0;
                this.questionRecords = [];
                this.showSummary = false;
                this.lastAnswerCorrect = false;
                this.lastAnswerWrong = false;
                this.isBestRecord = false;
                
                // 生成题目并启动计时
                this.generateQuestion();
                this.startTimer();
            },
            
            // 生成题目
            generateQuestion() {
                this.userAnswer = '';
                this.lastAnswerCorrect = false;
                this.lastAnswerWrong = false;
                
                if (this.trainingType === 'basic') {
                    this.generateBasicQuestion();
                } else {
                    this.generateSpecialQuestion();
                }
            },
            
            // 生成基础计算题目
            generateBasicQuestion() {
                let num1, num2, operator, answer, errorRange = this.errorRange;
                
                switch (this.trainingMode) {
                    case 'twoDigitAddSub':
                        num1 = Math.floor(Math.random() * 90) + 10;
                        num2 = Math.floor(Math.random() * (num1 - 10)) + 10;
                        const isAdd = Math.random() < 0.5;
                        operator = isAdd ? '+' : '-';
                        answer = isAdd ? num1 + num2 : num1 - num2;
                        errorRange = 0;
                        break;
                    case 'threeDigitAddSub':
                        num1 = Math.floor(Math.random() * 900) + 100;
                        num2 = Math.floor(Math.random() * num1);
                        const isAddThree = Math.random() < 0.5;
                        operator = isAddThree ? '+' : '-';
                        answer = isAddThree ? num1 + num2 : num1 - num2;
                        break;
                    case 'twoDigitMultiply':
                        num1 = Math.floor(Math.random() * 90) + 10;
                        num2 = Math.floor(Math.random() * 90) + 10;
                        operator = '×';
                        answer = num1 * num2;
                        break;
                    case 'twoDigitOneDigitMultiply':
                        num1 = Math.floor(Math.random() * 90) + 10;
                        num2 = Math.floor(Math.random() * 9) + 1;
                        operator = '×';
                        answer = num1 * num2;
                        break;
                    case 'threeDigitOneDigitDivide':
                        num2 = Math.floor(Math.random() * 8) + 2; // 2-9
                        answer = Math.floor(Math.random() * 100) + 20; // 20-119
                        num1 = answer * num2;
                        operator = '÷';
                        break;
                    case 'threeDigitPercentage':
                        num1 = Math.floor(Math.random() * 900) + 100;
                        const percentages = [10, 15, 20, 25, 30, 40, 50, 60, 70, 75, 80, 90];
                        num2 = percentages[Math.floor(Math.random() * percentages.length)];
                        operator = '×';
                        answer = num1 * (num2 / 100);
                        this.currentQuestion = {
                            question: `${num1} × ${num2}%`,
                            answer: answer,
                            errorRange: errorRange,
                            explanation: ''
                        };
                        return;
                    case 'squareWithin30':
                        num1 = Math.floor(Math.random() * 19) + 11; // 11-29
                        operator = '²';
                        answer = num1 * num1;
                        this.currentQuestion = {
                            question: `${num1}²`,
                            answer: answer,
                            errorRange: errorRange,
                            explanation: ''
                        };
                        return;
                    case 'twoDigitDivideThreeDigit':
                        num1 = Math.floor(Math.random() * 90) + 10;
                        num2 = Math.floor(Math.random() * 900) + 100;
                        operator = '÷';
                        answer = num1 / num2;
                        break;
                    case 'fiveDigitDivideThreeDigit':
                        num1 = Math.floor(Math.random() * 90000) + 10000;
                        num2 = Math.floor(Math.random() * 900) + 100;
                        operator = '÷';
                        answer = num1 / num2;
                        break;
                    case 'threeDigitDivideTwoDigit':
                        num1 = Math.floor(Math.random() * 900) + 100;
                        num2 = Math.floor(Math.random() * 90) + 10;
                        operator = '÷';
                        answer = num1 / num2;
                        break;
                    default:
                        num1 = Math.floor(Math.random() * 90) + 10;
                        num2 = Math.floor(Math.random() * 90) + 10;
                        operator = '+';
                        answer = num1 + num2;
                }
                
                this.currentQuestion = {
                    question: `${num1} ${operator} ${num2}`,
                    answer: answer,
                    errorRange: errorRange,
                    explanation: ''
                };
            },
            
            // 生成特殊计算题目
            generateSpecialQuestion() {
                switch (this.methodType) {
                    case 'tail-method':
                        this.generateTailMethodQuestion();
                        break;
                    case 'round-method':
                        this.generateRoundMethodQuestion();
                        break;
                    case 'proportion-method':
                        this.generateProportionMethodQuestion();
                        break;
                    case 'multi-addition':
                        this.generateMultiAdditionQuestion();
                        break;
                    case 'small-growth-estimation':
                        this.generateSmallGrowthEstimationQuestion();
                        break;
                    case 'threeDigitFraction1':
                        this.generateThreeDigitFraction1Question();
                        break;
                    case 'threeDigitFraction2':
                        this.generateThreeDigitFraction2Question();
                        break;
                    case 'fractionToPercentage':
                        this.generateFractionToPercentageQuestion();
                        break;
                    case 'threeDigitMultiply1_1':
                        this.generateThreeDigitMultiply1_1Question();
                        break;
                    case 'threeDigitMultiply0_9':
                        this.generateThreeDigitMultiply0_9Question();
                        break;
                    default:
                        this.generateTailMethodQuestion();
                }
            },
            
            // 尾数法题目生成 - 修改为支持加减混合运算
            generateTailMethodQuestion() {
                // 生成3-5个数字
                const count = Math.floor(Math.random() * 3) + 3;
                const numbers = [];
                let operators = [];
                
                // 生成第一个数字
                const firstDigits = Math.floor(Math.random() * 3) + 3; // 3-5位数
                const firstMin = Math.pow(10, firstDigits - 1);
                const firstMax = Math.pow(10, firstDigits) - 1;
                numbers.push(Math.floor(Math.random() * (firstMax - firstMin + 1)) + firstMin);
                
                // 生成后续数字和运算符
                for (let i = 1; i < count; i++) {
                    // 随机选择加法或减法
                    operators.push(Math.random() < 0.5 ? '+' : '-');
                    
                    // 生成3-5位数
                    const digits = Math.floor(Math.random() * 3) + 3;
                    const min = Math.pow(10, digits - 1);
                    const max = Math.pow(10, digits) - 1;
                    numbers.push(Math.floor(Math.random() * (max - min + 1)) + min);
                }
                
                // 构建题目字符串
                let questionText = numbers[0].toString();
                for (let i = 0; i < operators.length; i++) {
                    questionText += ` ${operators[i]} ${numbers[i + 1]}`;
                }
                
                // 计算结果并获取尾数
                let result = numbers[0];
                for (let i = 0; i < operators.length; i++) {
                    if (operators[i] === '+') {
                        result += numbers[i + 1];
                    } else {
                        result -= numbers[i + 1];
                    }
                }
                
                // 处理负数情况，确保尾数正确
                const tailResult = Math.abs(result) % 10;
                
                // 构建解释
                let tailExplanation = `${numbers[0] % 10}`;
                for (let i = 0; i < operators.length; i++) {
                    tailExplanation += ` ${operators[i]} ${numbers[i + 1] % 10}`;
                }
                tailExplanation += ` = ${tailResult}`;
                
                this.currentQuestion = {
                    question: questionText,
                    answer: tailResult,
                    errorRange: 0,
                    explanation: `尾数计算：${tailExplanation}`
                };
            },
            
            // 凑整法题目生成
            generateRoundMethodQuestion() {
                let num1 = Math.floor(Math.random() * 50) + 150;
                let num2 = Math.floor(Math.random() * 50) + 150;
                
                this.currentQuestion = {
                    question: `${num1} + ${num2}`,
                    answer: num1 + num2,
                    errorRange: this.errorRange,
                    explanation: '凑整法：将数字凑成整十、整百进行计算'
                };
            },
            
            // 415份数法题目生成
            generateProportionMethodQuestion() {
                // 随机生成三位数现期值
                const currentValue = Math.floor(Math.random() * 900) + 100; // 100-999
                
                // 随机生成增长率分母（2-20，对应1/2到1/20）
                const denominator = Math.floor(Math.random() * 19) + 2; // 2-20
                
                // 随机决定增长率是正的还是负的
                const isNegative = Math.random() < 0.3; // 30%概率为负增长率
                const growthRate = (1 / denominator) * 100; // 转换为百分比
                
                // 计算增量
                let increment;
                let formula;
                if (isNegative) {
                    // 负增长率：增量 = 现期值/(分母-1)
                    increment = currentValue / (denominator - 1);
                    formula = `${currentValue}/(${denominator}-1) = ${currentValue}/${denominator - 1}`;
                } else {
                    // 正增长率：增量 = 现期值/(分母+1)
                    increment = currentValue / (denominator + 1);
                    formula = `${currentValue}/(${denominator}+1) = ${currentValue}/${denominator + 1}`;
                }
                
                // 格式化增长率显示为百分数
                const rateDisplay = `${isNegative ? '-' : ''}${growthRate.toFixed(1)}%`;
                
                this.currentQuestion = {
                    question: `现期${currentValue}，增长率${rateDisplay}，求变化量`,
                    answer: Math.round(increment * 100) / 100, // 保留两位小数
                    errorRange: this.errorRange,
                    explanation: `415份数法：增量 = 现期值/(分母${isNegative ? '-' : '+'}1) = ${formula} = ${Math.round(increment * 100) / 100}`
                };
            },
            
            // 多位数相加题目生成 - 修改为随机三个数的加减混合运算
            generateMultiAdditionQuestion() {
                const numbers = [];
                const operators = [];
                
                // 生成三个数字（三位数或四位数）
                for (let i = 0; i < 3; i++) {
                    const digits = Math.random() < 0.5 ? 3 : 4; // 随机选择三位数或四位数
                    const min = Math.pow(10, digits - 1);
                    const max = Math.pow(10, digits) - 1;
                    const num = Math.floor(Math.random() * (max - min + 1)) + min;
                    numbers.push(num);
                }
                
                // 生成两个运算符（加或减）
                for (let i = 0; i < 2; i++) {
                    operators.push(Math.random() < 0.5 ? '+' : '-');
                }
                
                // 构建题目字符串
                let questionText = numbers[0].toString();
                for (let i = 0; i < operators.length; i++) {
                    questionText += ` ${operators[i]} ${numbers[i + 1]}`;
                }
                
                // 计算结果
                let result = numbers[0];
                for (let i = 0; i < operators.length; i++) {
                    if (operators[i] === '+') {
                        result += numbers[i + 1];
                    } else {
                        result -= numbers[i + 1];
                    }
                }
                
                this.currentQuestion = {
                    question: questionText,
                    answer: result,
                    errorRange: this.errorRange,
                    explanation: '多位数加减混合运算：按位计算，注意借位和退位'
                };
            },
            
            // 小增长率估增量法题目生成
            generateSmallGrowthEstimationQuestion() {
                // 随机生成三位数现期值
                const currentValue = Math.floor(Math.random() * 900) + 100; // 100-999
                
                // 随机生成小增长率（绝对值小于5%）
                const isNegative = Math.random() < 0.3; // 30%概率为负增长率
                const growthRateAbs = Math.random() * 4.8 + 0.2; // 0.2% - 4.9%
                const growthRate = isNegative ? -growthRateAbs : growthRateAbs;
                
                // 计算增量：现期 × 增长率的绝对值
                const increment = currentValue * (growthRateAbs / 100);
                
                // 格式化增长率显示
                const rateDisplay = `${isNegative ? '-' : ''}${growthRateAbs.toFixed(1)}%`;
                
                this.currentQuestion = {
                    question: `现期${currentValue}，增长率${rateDisplay}，估算变化量`,
                    answer: Math.round(increment * 100) / 100, // 保留两位小数
                    errorRange: this.errorRange,
                    explanation: `小增长率估增量法：增量 ≈ 现期值 × 增长率的绝对值 = ${currentValue} × ${growthRateAbs.toFixed(1)}% = ${Math.round(increment * 100) / 100}`
                };
            },
            
            // 三位数乘几分之一题目生成
            generateThreeDigitFraction1Question() {
                const num1 = Math.floor(Math.random() * 900) + 100;
                const denominators1 = [2, 3, 4, 5, 6, 8, 10];
                const num2 = denominators1[Math.floor(Math.random() * denominators1.length)];
                const answer = num1 / num2;
                
                this.currentQuestion = {
                    question: `${num1} × 1/${num2}`,
                    answer: answer,
                    errorRange: this.errorRange,
                    explanation: `三位数乘几分之一：${num1} × 1/${num2} = ${num1} ÷ ${num2} = ${answer}`
                };
            },
            
            // 三位数乘几分之二题目生成
            generateThreeDigitFraction2Question() {
                const num1 = Math.floor(Math.random() * 900) + 100;
                const denominators2 = [3, 5, 7, 9];
                const num2 = denominators2[Math.floor(Math.random() * denominators2.length)];
                const answer = (num1 * 2) / num2;
                
                this.currentQuestion = {
                    question: `${num1} × 2/${num2}`,
                    answer: answer,
                    errorRange: this.errorRange,
                    explanation: `三位数乘几分之二：${num1} × 2/${num2} = ${num1} × 2 ÷ ${num2} = ${answer}`
                };
            },
            
            // 20以内分化百题目生成
            generateFractionToPercentageQuestion() {
                const numerator = 1; // 分子固定为1
                const denominator = Math.floor(Math.random() * 19) + 2; // 分母为2-20
                const answer = (numerator / denominator) * 100;
                this.currentQuestion = {
                    question: `${numerator}/${denominator} = ?%`,
                    answer: answer,
                    errorRange: this.errorRange,
                    explanation: `分数转换为百分数：${numerator}/${denominator} = ${numerator} ÷ ${denominator} × 100% = ${answer.toFixed(1)}%`
                };
            },
            
            // 三位数乘1.1题目生成
            generateThreeDigitMultiply1_1Question() {
                const num1 = Math.floor(Math.random() * 900) + 100;
                const answer = num1 * 1.1;
                
                this.currentQuestion = {
                    question: `${num1} × 1.1`,
                    answer: answer,
                    errorRange: this.errorRange,
                    explanation: `三位数乘1.1：${num1} × 1.1 = ${num1} + ${num1} × 0.1 = ${num1} + ${num1 * 0.1} = ${answer}`
                };
            },
            
            // 三位数乘0.9题目生成
            generateThreeDigitMultiply0_9Question() {
                const num1 = Math.floor(Math.random() * 900) + 100;
                const answer = num1 * 0.9;
                
                this.currentQuestion = {
                    question: `${num1} × 0.9`,
                    answer: answer,
                    errorRange: this.errorRange,
                    explanation: `三位数乘0.9：${num1} × 0.9 = ${num1} - ${num1} × 0.1 = ${num1} - ${num1 * 0.1} = ${answer}`
                };
            },
            
            // 检查答案
            checkAnswer() {
                let userAnswer = this.userAnswer.trim();
                if (!userAnswer) {
                    uni.showToast({
                        title: '请输入答案',
                        icon: 'none'
                    });
                    return;
                }
                
                if (userAnswer.includes('%')) {
                    userAnswer = userAnswer.replace('%', '');
                }
                
                const userNum = parseFloat(userAnswer);
                const correctAnswer = this.currentQuestion.answer;
                const errorRange = this.currentQuestion.errorRange;
                
                let isCorrect;
                if (errorRange === 0) {
                    isCorrect = userNum === correctAnswer;
                } else {
                    const range = Math.abs(correctAnswer) * (errorRange / 100);
                    const min = correctAnswer - range;
                    const max = correctAnswer + range;
                    isCorrect = userNum >= min && userNum <= max;
                }
                
                // 设置答案反馈状态
                this.lastAnswerCorrect = isCorrect;
                this.lastAnswerWrong = !isCorrect;
                
                if (isCorrect) {
                    this.correctCount++;
                } else {
                    this.wrongCount++;
                }
                
                this.questionRecords.push({
                    question: this.currentQuestion.question,
                    userAnswer: userAnswer,
                    correctAnswer: correctAnswer.toString(),
                    isCorrect: isCorrect
                });
                
                // 立即切换到下一题
                this.currentQuestionIndex++;
                
                if (this.currentQuestionIndex >= this.questionCount) {
                    this.endTraining();
                } else {
                    this.generateQuestion();
                }
            },
            
            // 结束训练
            endTraining() {
                if (this.timerInterval) {
                    clearInterval(this.timerInterval);
                    this.timerInterval = null;
                }
                this.showSummary = true;
                this.saveRecord();
            },
            
            // 重新开始训练
            restartTraining() {
                this.startTraining();
            },
            
            // 保存记录
            saveRecord() {
                // 只有全对才能保存记录
                if (this.wrongCount > 0) {
                    console.log('存在错题，不保存记录');
                    this.isBestRecord = false;
                    return;
                }
                
                const recordData = {
                    modeType: this.trainingMode || this.methodType,
                    modeTitle: this.methodTitle || this.title,
                    totalQuestions: this.questionCount,
                    correctCount: this.correctCount,
                    wrongCount: this.wrongCount,
                    totalTime: this.totalMilliseconds / 1000 // 转换为秒
                };

                estimateRecordAdd(recordData).then(res => {
                    console.log('接口返回结果', res);
                    // 根据返回的code判断是否为最好成绩
                    if (res && res.code === 200) {
                        // code为200，说明是最好成绩
                        this.isBestRecord = true;
                        uni.showToast({
                            title: '恭喜！刷新最好成绩',
                            icon: 'success',
                            duration: 2000
                        });
                    } else {
                        // code不为200，说明不是最好成绩
                        this.isBestRecord = false;
                        const message = res && res.msg ? res.msg : '本次不是最好成绩，不予保存';
                        uni.showToast({
                            title: message,
                            icon: 'none',
                            duration: 2500
                        });
                    }
                }).catch(err => {
                    console.log('记录保存失败', err);
                    // 请求失败的情况
                    this.isBestRecord = false;
                    uni.showToast({
                        title: '网络错误，保存失败',
                        icon: 'error',
                        duration: 2000
                    });
                });
            },
            
            // 保存图片
            saveImage() {
                if (this.wrongCount > 0) {
                    uni.showToast({
                        title: '只有全对才能保存记录',
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }
                
                uni.showToast({
                    title: '自己截图保存吧！',
                    icon: 'success',
                    duration: 1500
                });
            },
            
            // 获取输入提示
            getInputPlaceholder() {
                if (this.isTailMethod) {
                    return '请输入结果的尾数（最后一位数字）';
                }
                return '请输入答案';
            },
            
            // 是否需要小数点
            needsDecimal() {
                return !this.isTailMethod;
            },
            
            // 是否需要百分号
            needsPercent() {
                return false;
            },
            
            // 是否需要负号
            needsMinus() {
                return false;
            },
            
            // 格式化时间显示
            formatTime() {
                const totalMs = this.totalMilliseconds;
                const minutes = Math.floor(totalMs / 60000);
                const seconds = Math.floor((totalMs % 60000) / 1000);
                const milliseconds = Math.floor((totalMs % 1000) / 100); // 保留一位小数
                
                // 格式化为 "分:秒.毫秒" 形式
                return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds}`;
            },
            
            // 答案格式化
            formatAnswer(value) {
                const num = parseFloat(value);
                if (isNaN(num)) {
                    return value.toString();
                }
                return num.toFixed(1);
            },
            
            // 开始计时
            startTimer() {
                // 清除可能存在的计时器
                if (this.timerInterval) {
                    clearInterval(this.timerInterval);
                }
                
                // 使用更精确的计时，每100ms更新一次
                this.timerInterval = setInterval(() => {
                    // 累加时间
                    this.totalMilliseconds += 100;
                    
                    // 更新格式化时间
                    this.formattedTime = this.formatTime();
                    
                    // 更新触发key，强制Vue刷新视图
                    this.timerUpdateKey++;
                }, 100);
            },
            
            // 输入数字
            inputNumber(num) {
                // 尾数法只允许输入一位数字
                if (this.isTailMethod) {
                    if (this.userAnswer.length >= 1) {
                        this.userAnswer = num; // 替换现有数字
                    } else {
                        this.userAnswer += num;
                    }
                    return;
                }
                
                if (num === '.' && this.userAnswer.includes('.')) return;
                if (num === '%' && this.userAnswer.includes('%')) return;
                this.userAnswer += num;
            },
            
            // 删除最后一个字符
            deleteLast() {
                this.userAnswer = this.userAnswer.slice(0, -1);
            },
            
            // 震动
            vibrate() {
                if (this.vibrationEnabled) {
                    uni.vibrateShort({ type: 'light' });
                }
            },
            
            // 触摸开始
            handleTouchStart(key) {
                if (!this.touchedKeys[key]) {
                    this.touchedKeys[key] = true;
                    switch (key) {
                        case 'restart':
                            this.vibrate();
                            this.restartTraining();
                            break;
                        case 'delete':
                            this.vibrate();
                            this.deleteLast();
                            break;
                        case 'confirm':
                            this.vibrate();
                            this.checkAnswer();
                            break;
                        default:
                            this.inputNumber(key);
                            this.vibrate();
                            break;
                    }
                }
            },
            
            // 触摸结束
            handleTouchEnd(key) {
                this.touchedKeys[key] = false;
            },
            
            // 切换小键盘
            toggleSmallKeyboard(e) {
                this.smallKeyboardEnabled = e.detail.value;
            },
            
            // 禁用输入框聚焦
            blurInput() {
                // 禁用系统键盘
            }
        },
        
        onLoad(options) {
            // 获取传递的参数
            this.trainingType = options.type || 'basic';
            this.trainingMode = options.mode || '';
            this.methodType = options.methodType || '';
            this.methodTitle = decodeURIComponent(options.methodTitle || options.modeTitle || '');
            this.questionCount = parseInt(options.questionCount) || 10;
            this.errorRange = parseInt(options.errorRange) || 5;
            
            // 设置页面标题
            if (this.trainingType === 'special') {
                this.title = this.methodTitle + '训练';
            } else {
                this.title = this.methodTitle ? this.methodTitle + '训练' : '基础计算训练';
            }
            
            // 开始训练
            this.startTraining();
        },
        
        beforeDestroy() {
            if (this.timerInterval) {
                clearInterval(this.timerInterval);
            }
        }
    }
</script>

<style lang="scss" scoped>
    .container {
        display: flex;
        flex-direction: column;
        background-color: #f8f8f8;
        height: 100vh;
        box-sizing: border-box;
        padding-bottom: env(safe-area-inset-bottom);
        overflow: hidden;
    }

    .training-area {
        display: flex;
        flex-direction: column;
        min-height: 0;
    }

    .status-card {
        background-color: #ffffff;
        border-radius: 12px;
        padding: 12px 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        margin-bottom: 8px;
    }

    .progress-container {
        margin-bottom: 12px;
    }

    .progress-bar {
        height: 6px;
        background-color: #f1f1f1;
        border-radius: 3px;
        overflow: hidden;
    }

    .progress-fill {
        height: 100%;
        background-color: #4CAF50;
        transition: width 0.3s ease;
    }

    .status-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .timer-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 6px 12px;
        background-color: #f0f7ff;
        border-radius: 6px;
    }

    .status-label {
        font-size: 10px;
        color: #666;
        margin-bottom: 2px;
    }

    .timer-text {
        font-size: 16px;
        font-weight: 700;
        color: #2196f3;
        letter-spacing: 0.5px;
    }

    .score-board {
        display: flex;
        gap: 12px;
    }

    .score-item {
        text-align: center;
    }

    .score-label {
        font-size: 10px;
        color: #666;
        display: block;
        margin-bottom: 2px;
    }

    .score-value {
        font-size: 14px;
        font-weight: 600;
        display: block;
    }

    .score-value.correct {
        color: #4CAF50;
    }

    .score-value.wrong {
        color: #F44336;
    }

    .question-area {
        flex: 0 0 auto;
        margin-bottom: 8px;
        max-height: 30vh;
        display: flex;
        align-items: center;
    }

    .question-card {
        background-color: #ffffff;
        border-radius: 12px;
        padding: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        text-align: center;
        display: flex;
        flex-direction: column;
        width: 100%;
    }

    .question-text {
        font-size: 28px;
        color: #333;
        line-height: 1.3;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16px;
        min-height: 60px;
        text-align: center;
    }

    // 尾数法提示样式
    .method-hint {
        font-size: 12px;
        color: #2196f3;
        margin-bottom: 12px;
        padding: 6px;
        background-color: #e3f2fd;
        border-radius: 4px;
        display: inline-block;
        align-self: center;
    }

    .question-explanation {
        font-size: 12px;
        color: #666;
        margin-bottom: 16px;
        padding: 8px;
        background-color: #f8f9fa;
        border-radius: 6px;
        line-height: 1.4;
    }

    .input-area input {
        width: 100%;
        height: 60px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        text-align: center;
        background-color: #f8f9fa;
        transition: all 0.3s ease;
        box-sizing: border-box;
        padding: 0 12px;
        font-size: 18px;
        line-height: 56px; /* height - border*2 = 60 - 4 = 56px */
        vertical-align: middle;
    }

    // 尾数法输入框更窄，提示用户只需要输入一位数字
    .input-area input:disabled {
        color: #333;
    }

    .input-area input.correct-input {
        border-color: #4CAF50;
        background-color: #f1f8e9;
    }

    .input-area input.wrong-input {
        border-color: #F44336;
        background-color: #ffebee;
    }

    .keyboard-container {
        width: 100%;
        background-color: #ffffff;
        border-radius: 12px 12px 0 0;
        padding: 12px;
        box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
        margin-top: auto;
    }

    .settings-row {
        display: flex;
        justify-content: space-between;
        padding: 8px 16px;
        background-color: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 12px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    }

    .setting-item {
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .setting-item text {
        font-size: 12px;
        color: #666;
    }

    .number-keyboard {
        width: 100%;
        max-width: 400px;
        margin: 0 auto;
        display: inline-block;
        transition: transform 0.3s ease;
    }

    .number-keyboard.small-keyboard {
        transform: scale(0.85);
        transform-origin: center;
    }

    .keyboard-row {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
    }

    .keyboard-row:last-child {
        margin-bottom: 0;
    }

    .key {
        flex: 1;
        padding: 14px 0;
        font-size: 16px;
        border: none;
        border-radius: 8px;
        background-color: #f8f9fa;
        color: #333;
        transition: all 0.15s ease;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        font-weight: 500;
    }

    .key:active {
        background-color: #e9ecef;
        transform: scale(0.96);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }

    .key.delete {
        background-color: #ffc107;
        color: white;
        font-size: 18px;
    }

    .key.clear {
        background-color: #17a2b8;
        color: white;
        font-size: 12px;
    }

    .key.confirm {
        background-color: #28a745;
        color: white;
        font-size: 12px;
    }

    .summary-area {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;
    }

    .summary-header {
        background-color: #ffffff;
        border-radius: 8px;
        padding: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        flex-shrink: 0;
    }

    .summary-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 12px;
        display: block;
        text-align: center;
    }

    .summary-stats {
        display: flex;
        justify-content: space-between;
    }

    .record-status {
        margin-top: 12px;
        text-align: center;
        border-radius: 6px;
    }

    .perfect-score {
        color: #4CAF50;
        font-size: 14px;
        font-weight: 600;
        background-color: #f1f8e9;
        padding: 6px 12px;
        border-radius: 6px;
        display: inline-block;
    }

    .good-score {
        color: #2196F3;
        font-size: 14px;
        font-weight: 600;
        background-color: #e3f2fd;
        padding: 6px 12px;
        border-radius: 6px;
        display: inline-block;
    }

    .imperfect-score {
        color: #FF9800;
        font-size: 14px;
        font-weight: 600;
        background-color: #fff8e1;
        padding: 6px 12px;
        border-radius: 6px;
        display: inline-block;
    }

    .stat-item {
        text-align: center;
        flex: 1;
    }

    .stat-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
        display: block;
    }

    .stat-value {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        display: block;
    }

    .stat-value.high-score {
        color: #4CAF50;
    }

    .stat-value.medium-score {
        color: #FF9800;
    }

    .stat-value.low-score {
        color: #F44336;
    }

    .summary-content-wrapper {
        background-color: #ffffff;
        border-radius: 8px;
        margin-bottom: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        flex: 1;
        min-height: 0;
    }

    .summary-content {
        height: 100%;
        overflow-y: auto;
    }

    .record-header {
        display: flex;
        background-color: #f8f9fa;
        padding: 8px;
        border-bottom: 1px solid #e9ecef;
        font-weight: 600;
        color: #495057;
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .record-header text {
        flex: 1;
        text-align: center;
        font-size: 12px;
    }

    .question-record {
        display: flex;
        padding: 6px;
        border-bottom: 1px solid #f8f9fa;
        min-height: 30px;
        align-items: center;
    }

    .question-record text {
        flex: 1;
        text-align: center;
        font-size: 14px;
        color: #495057;
        word-break: break-all;
        line-height: 1.3;
        padding: 2px;
    }

    .question-record.correct {
        background-color: #f8fff8;
    }

    .question-record.wrong {
        background-color: #fff8f8;
    }

    .action-buttons {
        display: flex;
        gap: 12px;
        flex-shrink: 0;
    }

    .restart-btn, .save-btn {
        flex: 1;
        padding: 12px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.2s ease;
    }

    .restart-btn {
        background-color: #4CAF50;
        color: white;
    }

    .save-btn {
        background-color: #2196f3;
        color: white;
    }

    .restart-btn:active, .save-btn:active {
        opacity: 0.9;
        transform: scale(0.98);
    }

    // 适配小屏幕手机
    @media screen and (max-width: 360px) {
        .question-text {
            font-size: 24px;
        }
        
        .key {
            padding: 12px 0;
            font-size: 14px;
        }
        
        .timer-text {
            font-size: 14px;
        }
        
        .input-area input {
            font-size: 16px;
            padding: 10px 12px;
        }
    }

    // 适配中等屏幕手机
    @media screen and (min-width: 375px) and (max-width: 414px) {
        .question-text {
            font-size: 30px;
        }
        
        .key {
            padding: 16px 0;
            font-size: 16px;
        }
    }

    // 适配大屏幕手机
    @media screen and (min-width: 414px) {
        .question-text {
            font-size: 32px;
        }
        
        .key {
            padding: 18px 0;
            font-size: 18px;
        }
        
        .keyboard-container {
            padding: 16px;
        }
    }
</style>
